<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\Guzzle;
use Illuminate\Support\Facades\DB;
use Log;
use Symfony\Component\HttpKernel\Exception\HttpException;

class RechargeController extends Controller
{
    public function createRechargeLog($data)
    {
        //充值日志
        if(isset($data['i_product_id']) && $data['i_product_id'] && $data['type']==1){
            $otw_product_id = DB::table('tbl_bill_open_product')->where('i_product_id',$data['i_product_id'])->value('i_otw_product_id');
            $ti_type = 1;
        } else {
            $otw_product_id = $data['i_product_id'];
            $ti_type = 2;
        }
        $reLog = array(
            'vc_account' => isset($data['vc_account'])?$data['vc_account']:'',
            'out_trade_no' => $data['out_trade_no'],
            'openid' => $data['openid'],
            'i_valid_days' => $data['i_valid_days'],
            'i_product_id' => $otw_product_id,
            'vc_product_name' => $data['vc_product_name'],
            'product_price' => $data['product_price'],
            'amount' => $data['product_price'],
            'dt_order_time' => date('Y-m-d H:i:s', time()),
            'ti_pay_status' => 0,
            'ti_type' => $ti_type,
            'ti_provider' => $data['provider'],
            'vc_imsi' => isset($data['vc_imsi'])? $data['vc_imsi']: ''
        );
        DB::table('tbl_product_recharge_log')->insert($reLog);
    }

    public function doRecharge()
    {
        if(isset($_POST['order_id']) && $_POST['order_id']){
            $order_id = $_POST['order_id'];
        } else {
            Log::info("参数：order_id  parameter error");
            throw new HttpException(403,'order_id  parameter error');
        }
        $data = DB::table('tbl_product_recharge_log')->where('out_trade_no',$order_id)->first();
        $data = (new EntranceController())->object_to_array($data);
        $nickName = DB::table('wx_users')->where('openid',$data['openid'])->value('nickname');
        if(!$data['ti_pay_status']){
            Log::info("参数：ti_pay_status  parameter error");
            throw new HttpException(403,'ti_pay_status  parameter error');
        }
        $mainProduct = array();
        $Guzzle = new Guzzle();
        $Auth = new AuthController();
        $token = $Auth->getToken();
        $giftsProducts = array();
        $bossProducts = $Guzzle->guzzle_post(config('app.boss_api_url'), '/v1/queryOtwBossProduct', [$data['i_product_id']], [
            'Content-type' => 'application/json',
            'Authorization' => $token
        ], 'json');
        //充套餐
        $productId = $data['i_product_id'];
        $mainProduct[0]['productId'] = $bossProducts['main_productId'][$productId];
        $mainProduct[0]['type'] = 'days';
        $mainProduct[0]['num'] = $data['i_valid_days'];
        $mainProduct[0]['productName'] = $data['vc_product_name'];
        $mainProduct[0]['account'] = $data['vc_account'];
        if (isset($bossProducts['gifts_productId'][$productId]) && $bossProducts['gifts_productId'][$productId]) {
            $giftsProducts[1]['productId'] = intval($bossProducts['gifts_productId'][$productId]);
            $giftsProducts[1]['type'] = 'present';
            $giftsProducts[1]['num'] = intval($bossProducts['gifts_productId'][$productId]);
            $giftsProducts[1]['productName'] = $data['vc_product_name'];
            $giftsProducts[1]['account'] = $data['vc_account'];
        }
        //充值日志
        $reLog = array();
        $reLog['vc_account'] = $data['vc_account'];
        $reLog['ti_type'] = 1;
        $reLog['dt_operate_time'] = date('Y-m-d H:i:s', time());
        if (is_array($giftsProducts) && count($giftsProducts) > 0) {
            $requestData = array_merge($mainProduct, $giftsProducts);
        } else {
            $requestData = $mainProduct;
        }
        if (!is_array($token)) {
            $result = $Guzzle->guzzle_post(config('app.boss_api_url'), '/v2/top-up', $requestData, [
                'Content-type' => 'application/json', 'Authorization' => $token, 'http_errors' => true
            ], 'json');
            if (isset($result['status']) && $result['status'] == 'error') {
                Log::info( isset($result['message'][0]['description']) ? $result['message'][0]['description'] : $result['message']);
                return response([
                    'success' => false,
                    'message' => isset($result['message'][0]['description']) ? $result['message'][0]['description'] : $result['message']
                ], 203);
            } else {
                $sucAccounts = array();
                $failAccounts = array();
                if (isset($result['success'])) {
                    foreach ($result['success'] as $v) {
                        $sucAccounts[] = $v['requestData']['account'];
                    }
                }
                if (isset($result['failure'])) {
                    foreach ($result['failure'] as $value) {
                        $failAccounts[$value['requestData']['account']] = $value['msg'];
                    }
                }
                $sendBoss = array('odpqKt4kbTuAk_7pFXuk69Y1BFqs','odpqKt2HuJ9zwz0clCKIA4XkllKw');
                $Entrance = new EntranceController();
                if (in_array($reLog['vc_account'], $sucAccounts)) {
                    $reLog['ti_status'] = 1;
                    $reLog['te_description'] = 'Success';
                    $Entrance->sendMsg($data['openid'],$data['i_id'],'恭喜'.$nickName.'充值成功！', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'祝您生活愉快，欢迎您下次继续充值！');
                    foreach($sendBoss as $boss_openid){
                        $Entrance->sendMsg($boss_openid,$data['i_id'],'您好！老板，有新订单了，恭喜'.$nickName.'充值成功！IMSI：'.$data['vc_imsi'].'，Provider：'.$this->providerName($data['ti_provider']), $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'祝您生活愉快！');
                    }
                    Log::info('充值成功：'.$reLog['vc_account'].' description success');
                } else {
                    $reLog['ti_status'] = 0;
                    $reLog['te_description'] = $failAccounts[$reLog['vc_account']];
                    $Entrance->sendMsg($data['openid'],$data['i_id'],'很抱歉!'.$nickName.'充值失败', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'请联系客服，为您服务！');
                    foreach($sendBoss as $boss_openid){
                        $Entrance->sendMsg($boss_openid,$data['i_id'],'您好！老板，有新订单了，很抱歉'.$nickName.'充值失败！IMSI：'.$data['vc_imsi'], $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'请联系客服及时处理！');
                    }
                    Log::info('充值失败：'.$reLog['vc_account']. $reLog['te_description']);
                }
                DB::table('tbl_product_recharge_log')->where('out_trade_no',$order_id)->update($reLog);
                $have = DB::table('users_bind')->where(['i_openid'=>$data['openid'], 'vc_account'=>$data['vc_account']])->first();
                if(!$have){
                    $bindTime = date('Y-m-d H:i:s', time());
                    DB::table('users_bind')->insert(array('i_openid'=>$data['openid'],'vc_account'=>$data['vc_account'],'dt_bind_time'=>$bindTime,'ti_type'=>2));
                }
            }
            return $result;
        } else {
            Log::info('充值失败：'.$reLog['vc_account'].' token过期');
            throw new HttpException(403, $token['message']);
        }
    }

    public function buySim()
    {
        if(isset($_POST['order_id']) && $_POST['order_id']){
            $order_id = $_POST['order_id'];
        } else {
            Log::info("参数：order_id  parameter error");
            throw new HttpException(403,'order_id  parameter error');
        }
        $data = DB::table('tbl_product_recharge_log')->where('out_trade_no', $order_id)->first();
        $data = (new EntranceController())->object_to_array($data);
        $nickName = DB::table('wx_users')->where('openid',$data['openid'])->value('nickname');
        if(!$data['ti_pay_status']){
            Log::info("参数：ti_pay_status  parameter error");
            throw new HttpException(403,'ti_pay_status  parameter error');
        }
        $Guzzle = new Guzzle();
        $Auth = new AuthController();
        $token = $Auth->getToken();
        $productId = $data['i_product_id'];
        $requestData = array(
            'productId'=>$productId
        );
        $result = $Guzzle->guzzle_post(config('app.boss_api_url'), '/buy-esim', $requestData, [
            'Content-type' => 'application/json', 'Authorization' => $token, 'http_errors' => true
        ], 'json');
        $reLog = array();
        $reLog['ti_type'] = 2;
        $reLog['dt_operate_time'] = date('Y-m-d H:i:s', time());
        $sendBoss = array('odpqKt4kbTuAk_7pFXuk69Y1BFqs','odpqKt2HuJ9zwz0clCKIA4XkllKw');
        $Entrance = new EntranceController();
        if($result['success']){
            $reLog['vc_account'] = $result['account'];
            $reLog['esim_url'] = $result['url'];
            $reLog['esim_msg'] = 'success';
            $reLog['ti_status'] = 1;
            $reLog['ti_sign'] = 0;
            $reLog['vc_imsi'] = substr($result['account'],1);
            $Entrance->sendMsg($data['openid'],$data['i_id'],'恭喜'.$nickName.'购买成功！', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'祝您生活愉快，欢迎您下次继续购买！');
            foreach($sendBoss as $boss_openid){
                $Entrance->sendMsg($boss_openid,$data['i_id'],'您好！老板，有新订单了，恭喜'.$nickName.'购买成功！IMSI：'.$reLog['vc_imsi'].'，Provider：'.$this->providerName($data['ti_provider']), $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'祝您生活愉快！');
            }
            Log::info('购买成功：'.$reLog['vc_account'].' description success');
        }else{
            $reLog['vc_account'] = isset($result['account'])? $result['account']:'';
            $reLog['esim_url'] = '';
            $reLog['esim_msg'] = $result['msg'];
            $reLog['ti_status'] = 0;
            $reLog['ti_sign'] = 2;
            $Entrance->sendMsg($data['openid'],$data['i_id'],'很抱歉!'.$nickName.'购买失败', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'请联系客服，为您服务！');
            foreach($sendBoss as $boss_openid){
                $Entrance->sendMsg($boss_openid,$data['i_id'],'您好！老板，有新订单了，很抱歉'.$nickName.'购买失败！', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'请联系客服，及时处理！');
            }
            Log::info('购买失败：'.$reLog['esim_msg']);
        }
        DB::table('tbl_product_recharge_log')->where('out_trade_no', $order_id)->update($reLog);
        if(isset($result['account']) && $result['account']){
            $have = DB::table('users_bind')->where(['i_openid'=>$data['openid'], 'vc_account'=>$result['account']])->first();
            if(!$have){
                $bindTime = date('Y-m-d H:i:s', time());
                DB::table('users_bind')->insert(array('i_openid'=>$data['openid'],'vc_account'=>$result['account'],'dt_bind_time'=>$bindTime,'ti_type'=>2));
            }
        }
        return $result;
    }
    public function providerName($provider){
        if(!$provider){
            return '';
        }
        $provider_data = array(
            '1' => 'SH',
            '2' => 'CUHK',
            '3' => 'SMT',
            '4' => 'CHKT',
            '5' => 'CSL',
            '6' => '3HK',
            '7' => 'APT',
            '8' => 'BICS',
            '9' => 'AIS',
            '10' => 'ORG',
            '11' => 'CMCC',
            '12' => 'TEST',
            '50' => 'BICS_EX',
            '51' => 'CITIC_EX',
            '52' => 'CUHK_EX',
            '53' => 'IPLOOK_EX',
        );
      return $provider_data[$provider];
    }
}